package UpdatePhysAction;

use strict;

use Athena::WebAPI::Response;
use Athena::PhysView;

sub execute {
  my $stInvocant = shift(@_);
  my $rRequest = shift(@_);
  my $rConn = shift(@_);
  my %hParams = ( @_ );
  my $stParams = \%hParams;
  my $rResponse = undef;
  my $stActionName = 'UpdatePhysAction';
  $rRequest->action($stActionName);
  my $stAction = $rRequest->param($stActionName);
  my $stErrMsg = "";
  my $stLb = $rRequest->cookie('AthenaEngineUrl') 
    || $rRequest->cookie('AthenaEngineHost') 
      . ":" . $rRequest->cookie('AthenaEnginePort');

  my $rPhyss = Athena::Engine::Phys->new($rConn);
  # refresh status from server
  # we need this to get idx numbers
  $rPhyss->refresh();
  # send updates
  if ($rRequest->param('need_update') eq '1') {
    my @arUpdateCols = ('on', 'up', 'in');
    my $key;
    foreach $key (keys(%{$rPhyss->{table}})) {
      my $stCol;
      foreach $stCol (@arUpdateCols) {
	my $stParamVal = $rRequest->param("idx.".$key.".".$stCol);
	# only update if different
	if ($stParamVal ne $rPhyss->{table}->{$key}->{$stCol}) {
	  $rPhyss->{table}->{$key}->{update} = 1;
	  if ($stParamVal) {
	    $rPhyss->{table}->{$key}->{$stCol} = 1;
	  }
	  else {
	    $rPhyss->{table}->{$key}->{$stCol} = 0;
	  }
	}
      }
    }
    $rPhyss->update();
  }

  my $rHiddenFields = {
		       $rRequest->getActionParam() => $rRequest->action(),
		       $stActionName => '',
		       'need_update' => 0,
		      };

  # begin display pref handling
  # no update of options in update phys mode
  my @arShowCols = undef;
  if ($rRequest->cookie('AthenaShowCols')) {
    @arShowCols = split(/,/, $rRequest->cookie('AthenaShowCols'));
  }
  my %hRenameCols = undef;
  if (@arShowCols) {
    if ($rRequest->cookie('AthenaMvCols')) {
      my $keyval;
      my @arMvCols = split(/,/, $rRequest->cookie('AthenaMvCols')); 
      for $keyval (@arMvCols) {
	my ($key, $val);
	($key, $val) = split(/=/, $keyval);
	$hRenameCols{$key} = $val;
      }
    }
  }

  my $rFarms = '0';
  # the ! case catches the default view, which contains farms
  if ((! @arShowCols) || (grep('farms', @arShowCols))) {
    $rFarms = Athena::Engine::Farm->new($rConn);
    $rFarms->refresh();
  }

  my $rView = PhysView->new('lb' => $stLb,
			    'err_msg' => $stErrMsg,
			    'hidden_fields' => $rHiddenFields,
			    'action_name' => $stActionName,
			    'body_style' => $stParams->{body_style},
			    'table_style' => $stParams->{table_style},
			    'physs' => $rPhyss,
			    'farms' => $rFarms,
			    'options' => '0',
			    'show_cols' => \@arShowCols || "0",
			    'mv_cols' => \%hRenameCols || "0"
			   );

  $rResponse = Response->new($rView);
  
  return $rResponse;
}

1;
